import axios from 'axios'
import { RESPONSE_MODE } from '../assets/types'
import { useAuthStore } from '@/stores'
import { ref } from 'vue'

export function useChat(chatApi: string, apiKey: string, user: string, _agent: string) {
  const REQUEST_HEADERS = {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  }

  const store = useAuthStore()
  const { token } = store
  const deviceId = ref('')
  const changeDeviceId = (id: string) => {
    deviceId.value = id
  }
  /**
   * @param query           用户输入
   * @param conversation_id 可选会话 ID
   * @param onMessage       每收到一段 SSE 文本回调
   */
  async function fetchChat(
    query: string,
    conversation_id: string | undefined,
    onMessage: (chunk: {
      conversation_id: string
      event: string
      id: string
      message_id: string
      task_id: string
      answer: string
    }) => void,
    parent_message_id?: string,
    deviceId?: string
  ) {
    // 记录上一次处理到的字符串长度
    let lastIndex = 0
    // buffer 用来拼凑残留的半条 SSE 事件
    let buffer = ''
    // 发送请求，可根据不同接口，传入不同的参数，这里是流式输出内容，封装了SSE的实现
    await axios.post(
      `${chatApi}/chat-messages`,
      {
        // query: agent === 'page-navigation' ? `${query}<令牌>${token}</令牌>` : `${query}`,
        query,
        response_mode: RESPONSE_MODE.STREAMING,
        conversation_id,
        files: [],
        inputs: { token: `Bearer ${token}`, id: deviceId ?? undefined },
        user,
        parent_message_id,
      },
      {
        headers: REQUEST_HEADERS,
        responseType: 'text', // 必须 text 才能拿到字符串
        onDownloadProgress: ({ event }) => {
          // 注意：这里用 responseText 而不是 response（两者等同于 text）
          const xhr = event.currentTarget as XMLHttpRequest
          const fullText = xhr.responseText
          // 截取本次新增的字符串
          const delta = fullText.substring(lastIndex)
          lastIndex = fullText.length

          buffer += delta
          // 按 SSE 事件分隔符 "\n\n" 拆分
          const parts = buffer.split('\n\n')
          // 最后一段可能残缺，留给下次循环
          buffer = parts.pop() ?? ''

          for (const part of parts) {
            if (!part.startsWith('data:')) continue
            const data = part.replace(/^data:\s*/, '').trim()
            if (data === '[DONE]') {
              return
            }
            try {
              const responseText = data.replace(/^data: \s*/, '')
              const json = JSON.parse(responseText)
              onMessage(json)
            } catch (err) {
              console.warn('解析 SSE JSON 失败：', err)
            }
          }
        },
      }
    )
  }

  // 取消任务
  const cancelTask = async (task_id: string) => {
    console.log(task_id, 'task_id')
    const res = await axios.post(
      `${chatApi}/chat-messages/${task_id}/stop`,
      {
        user,
      },
      {
        headers: REQUEST_HEADERS,
      }
    )
    return res
  }
  return { fetchChat, cancelTask, changeDeviceId }
}
